package com.example.practice;


import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.google.gson.Gson;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.http.GET;


/**
 * A simple {@link Fragment} subclass.
 */
public class LifeFragment extends Fragment implements View.OnClickListener {

    private View view;
    private TextView lifewendu;
    private TextView lifewenducha;
    private LineChart lifemlineChar;
    private ImageView life;
    private ViewPager vpage;
    private TabLayout lifetab;
    private int i = 0;
    private int j = 1;
    private int webdu;
    private ArrayList<Entry> valuesMax;
    private ArrayList<Entry> valuesMin;
    private TextView life1;
    private TextView life2;
    private TextView life3;
    private TextView life4;
    private TextView life5;
    private SQLiteDatabase db;
    private Timer timer;
    private TimerTask timerTask;
    public LifeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        timer=null;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_life, container, false);
        initView();
        SqliteUsers sUsers = new SqliteUsers(getContext());
        db= sUsers.getReadableDatabase();
        timer=new Timer();
        timerTask=new TimerTask() {
            @Override
            public void run() {
                initData();
            }
        };
        timer.schedule(timerTask,0,3000);
        return view;
    }

    private void initUi1() {
        lifewendu.setText(webdu + "°");
        int i = webdu - (int) (Math.random() * 5);
        int j = webdu + (int) (Math.random() * 5);
        lifewenducha.setText("今天：" + i + "-" + j + "℃");
        lifemlineChar.setTouchEnabled(false);
        lifemlineChar.setDescription(null);
        valuesMax = new ArrayList<>();
        valuesMin = new ArrayList<>();
        for (int a = 1; a <= 6; a++) {
            valuesMax.add(new Entry(a, j + (int) (Math.random() * 4) - 2));
            valuesMin.add(new Entry(a, i + (int) (Math.random() * 4) - 2));
        }
        LineDataSet setMax = new LineDataSet(valuesMax, "");
        setMax.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        setMax.setDrawValues(true);
        setMax.setValueTextSize(10);
        setMax.setFormSize(0);
        setMax.setDrawCircles(true);
        setMax.setDrawCircleHole(false);
        setMax.setLineWidth(2f);
        setMax.setCircleColor(Color.parseColor("#FF0000"));
        setMax.setColor(Color.parseColor("#FF0000"));
        LineDataSet setMin = new LineDataSet(valuesMin, "");
        setMin.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);
        setMin.setDrawValues(true);
        setMin.setValueTextSize(10);
        setMin.setFormSize(0);
        setMin.setDrawCircles(true);
        setMin.setDrawCircleHole(false);
        setMin.setLineWidth(2f);
        setMin.setCircleColor(Color.parseColor("#3F51B5"));
        setMin.setColor(Color.parseColor("#3F51B5"));
        XAxis xAxis = lifemlineChar.getXAxis();
        xAxis.setAxisLineColor(Color.parseColor("#FFFFFF"));
        xAxis.setDrawGridLines(false);
        xAxis.setAxisMinimum(1f);
        xAxis.setGranularity(1f);
        xAxis.setPosition(XAxis.XAxisPosition.TOP);
        final List<String> lists = new ArrayList<>();
        lists.add("昨天");
        lists.add("今天");
        lists.add("明天");
        lists.add(time(2));
        lists.add(time(3));
        lists.add(time(4));
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return lists.get((int) value - 1);
            }
        });
        YAxis axisRight = lifemlineChar.getAxisRight();
        axisRight.setEnabled(false);
        YAxis axisLeft = lifemlineChar.getAxisLeft();
        axisLeft.setAxisLineColor(Color.parseColor("#FFFFFF"));
        axisLeft.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return "";
            }
        });
        axisLeft.setDrawGridLines(true);
        LineData data = new LineData(setMax);
        data.addDataSet(setMin);
        lifemlineChar.setData(data);
        lifemlineChar.invalidate();
    }

    private String time(int i) {
        SimpleDateFormat formatdata = new SimpleDateFormat("E");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, i);
        Date date = calendar.getTime();
        String format = formatdata.format(date);
        return format;

    }

    @Override
    public void onClick(View view) {
        j=0;
        i = 0;
        initData();
    }

    private interface BlogSever {
        @GET("getAirCondition")
        Call<ResponseBody> getBlog();
    }

    private void initData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://hh1.me:5001/")
                .build();
        BlogSever blogSever = retrofit.create(BlogSever.class);
        Call<ResponseBody> blog = blogSever.getBlog();
        blog.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    List<Car8Users> list = new ArrayList<>();
                    Car8Users car8Users = new Gson().fromJson(string, Car8Users.class);
                    list.add(car8Users);
                    if(j==1){
                        ContentValues values = new ContentValues();
                        values.put("weather1",list.get(0).get温度());
                        values.put("weather2",list.get(0).get相对湿度());
                        values.put("weather3",list.get(0).get紫外线强度());
                        values.put("weather4",list.get(0).getCo2());
                        values.put("weather5",list.get(0).get_$Pm25260());
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ss");
                        Date date = new Date(System.currentTimeMillis());
                        values.put("weather7",simpleDateFormat.format(date));
                        db.insert("weather",null,values);
                        Cursor info1;
                        info1= db.query("weather", null, null,null, null, null, null);
                        for(;info1.getCount()>20;){
                            info1.moveToFirst();
                            db.delete("weather","weather7=?", new String[]{info1.getString(info1.getColumnIndex("weather7"))});
                            info1=db.query("weather", null, null,null, null, null, null);
                        }
                        initUi2(list);
                    }
                    webdu = list.get(0).get温度();
                    if (i == 0) {
                        j = 1;
                        i = 1;
                        initUi1();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    private void initUi2(List<Car8Users> list) {
        int 紫外线强度 = list.get(0).get紫外线强度();
        int 温度 = list.get(0).get温度();
        int co2 = list.get(0).getCo2();
        int pm25260 = list.get(0).get_$Pm25260();
        if(紫外线强度<=1000){
            life1.setText("弱("+紫外线强度+")\n辐射较弱，涂擦SPF12~15、PA+护肤品");
        }if(紫外线强度<=3000){
            life1.setText("中等("+紫外线强度+")\n涂擦SPF大于15、PA+防晒护肤品");
        }else {
            life1.setText("强("+紫外线强度+")\n尽量减少外出，需要涂抹高倍数防晒霜");
        }
        if(温度<8){
            life2.setText("较易发("+温度+")\n温度低，风较大，较易发生感冒，注意防护");
        }else {
            life2.setText("少发("+温度+")\n无明显降温，感冒机率较低");
        }
        if(温度<12){
            life3.setText("冷("+温度+")\n建议穿长袖衬衫、单裤等服装");
        }if(温度<21){
            life3.setText("舒适("+温度+")\n建议穿短袖衬衫、单裤等服装");
        } else {
            life3.setText("热("+温度+")\n适合穿T恤、短薄外套等夏季服装");
        }
        if(co2<3000){
            life4.setText("适宜("+co2+")\n气候适宜，推荐您进行户外运动");
        }if(co2<6000){
            life4.setText("中("+co2+")\n易感人群应适当减少室外活动");
        } else {
            life4.setText("较不宜("+co2+")\n空气氧气含量低，请在室内进行休闲运动");
        }
        if(pm25260<30){
            life5.setText("优("+pm25260+")\n空气质量非常好，非常适合户外活动，趁机出去多呼吸新鲜空气");
        }if(pm25260<100){
            life5.setText("良("+pm25260+")\n易感人群应适当减少室外活动");
        } else {
            life5.setText("污染("+pm25260+")\n空气质量差，不适合户外活动");
        }
    }

    private void initView() {
        lifewendu = (TextView) view.findViewById(R.id.lifewendu);
        lifewenducha = (TextView) view.findViewById(R.id.lifewenducha);
        lifemlineChar = (LineChart) view.findViewById(R.id.lifemlineChar);
        life = (ImageView) view.findViewById(R.id.life);
        life.setOnClickListener(this);
        lifetab = (TabLayout) view.findViewById(R.id.lifetab);
        vpage = (ViewPager) view.findViewById(R.id.vpage);
        List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new AerFragment());
        fragmentList.add(new WenduFragment());
        fragmentList.add(new ShiduFragment());
        fragmentList.add(new Co2Fragment());
        FragmentWather fragmentWather = new FragmentWather(getChildFragmentManager(), fragmentList);
        vpage.setAdapter(fragmentWather);
        lifetab.setupWithViewPager(vpage);
        life2 = (TextView) view.findViewById(R.id.life2);
        life1 = (TextView) view.findViewById(R.id.life1);
        life3 = (TextView) view.findViewById(R.id.life3);
        life4 = (TextView) view.findViewById(R.id.life4);
        life5 = (TextView) view.findViewById(R.id.life5);
    }

}
